package com.nnnu.wsnackshop.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nnnu.wsnackshop.pojo.entity.Riders;
import com.nnnu.wsnackshop.pojo.entity.Users;
import com.nnnu.wsnackshop.service.IRidersService;
import com.nnnu.wsnackshop.service.IUsersService;
import com.nnnu.wsnackshop.utils.JwtToken;
import com.nnnu.wsnackshop.utils.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class JwtRealm extends AuthorizingRealm {

    private final IUsersService userService;
    private final IRidersService ridersService;
    private static final Logger log = LoggerFactory.getLogger(JwtRealm.class);

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        String token = (String) authcToken.getCredentials();
        String username = JwtUtil.getUsername(token);
        if (username == null || !JwtUtil.verify(token, username)) {
            throw new AuthenticationException("Invalid JWT Token");
        }

        // 获取用户类型
        String userType = JwtUtil.getUserTypeFromToken(token);

        if ("rider".equals(userType)) {
            // 骑手认证
            Riders rider = JwtUtil.getRiderFromToken(token);
            if (rider == null) {
                // 如果token中没有骑手信息，则从数据库查询
                LambdaQueryWrapper<Riders> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Riders::getPhone, username);
                rider = ridersService.getOne(queryWrapper);
            }

            if (rider == null) {
                throw new UnknownAccountException("Rider not found");
            }
        } else {
            // 普通用户认证
            Users user = JwtUtil.getUserFromToken(token);

            // 如果token中没有用户信息，则从数据库查询
            if (user == null) {
                user = userService.getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, username));
            }

            if (user == null) {
                throw new UnknownAccountException("User not found");
            }
        }

        return new SimpleAuthenticationInfo(token, token, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(@NonNull PrincipalCollection principals) {
        String token = (String) principals.getPrimaryPrincipal();
        String username = JwtUtil.getUsername(token);
        String userType = JwtUtil.getUserTypeFromToken(token);

        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();

        if ("rider".equals(userType)) {
            // 骑手角色和权限
            roles.add("rider");
            permissions.add("rider:login");
            permissions.add("rider:orders");
            permissions.add("rider:profile");
            log.info("骑手 {} 的角色: {}", username, roles);
        } else {
            // 普通用户角色和权限
            roles = userService.getRoleStrings(username);
            permissions = userService.getPermissionStrings(username);

            // 如果用户没有角色，默认给予user角色（用于访问用户端接口）
            if (roles == null || roles.isEmpty()) {
                roles = new HashSet<>();
                roles.add("user");
                log.info("用户 {} 没有分配角色，默认给予user角色", username);
            } else {
                log.info("用户 {} 的角色: {}", username, roles);
            }
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 清除当前用户的权限认证缓存
     *
     * @param principals 权限信息
     */
    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public JwtRealm(IUsersService userService, IRidersService ridersService) {
        this.userService = userService;
        this.ridersService = ridersService;
        // 启用缓存
        setCachingEnabled(true);
        setAuthenticationCachingEnabled(true);
        setAuthenticationCacheName("shiro:cache:authentication");
        setAuthorizationCachingEnabled(true);
        setAuthorizationCacheName("shiro:cache:authorization");
    }
}
